package com.loong.system.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loong.framework.dto.IdParamDTO;
import com.loong.framework.utils.CommonUtil;
import com.loong.framework.utils.SystemUtil;
import com.loong.system.dto.ConfigAddDTO;
import com.loong.system.dto.ConfigPageDTO;
import com.loong.system.dto.ConfigUpdateDTO;
import com.loong.system.entity.Config;
import com.loong.system.service.IConfigService;
import com.loong.system.vo.ConfigDetailVO;
import com.loong.system.vo.ConfigListVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "配置操作 API")
@RestController
@RequestMapping("/api/v1.0/config")
public class ConfigController {

  @Resource private IConfigService configService;

  @SaCheckRole("root")
  @Operation(summary = "新增")
  @PostMapping("/add")
  public void add(@RequestBody @Valid ConfigAddDTO addDTO) {
    Config config = SystemUtil.buildResource(addDTO, Config.class);
    configService.save(config);
  }

  @SaCheckRole("root")
  @Operation(summary = "删除")
  @PostMapping("/remove")
  public void remove(@RequestBody @Valid IdParamDTO idParamDTO) {
    configService.removeById(idParamDTO.getId());
  }

  @SaCheckRole("root")
  @Operation(summary = "更新")
  @PostMapping("/update")
  public void update(@RequestBody @Valid ConfigUpdateDTO updateDTO) {
    Config config = SystemUtil.buildResource(updateDTO, Config.class);
    configService.updateById(config);
  }

  @SaCheckRole("root")
  @Operation(summary = "详情")
  @PostMapping("/detail")
  public ConfigDetailVO detail(@RequestBody @Valid IdParamDTO idParamDTO) {
    Config config = configService.getById(idParamDTO.getId());
    return SystemUtil.buildResource(config, ConfigDetailVO.class);
  }

  @SaCheckRole("root")
  @Operation(summary = "获取配置列表")
  @PostMapping("/getConfigList")
  public Page<ConfigListVO> getConfigList(@RequestBody @Valid ConfigPageDTO pageDTO) {
    String configName = pageDTO.getConfigName();
    String description = pageDTO.getDescription();

    Page<Config> page = SystemUtil.buildPageFromDTO(pageDTO, Config.class);
    page =
        configService
            .lambdaQuery()
            .like(CommonUtil.notNullOrEmpty(configName), Config::getConfigName, configName)
            .like(CommonUtil.notNullOrEmpty(description), Config::getDescription, description)
            .orderByDesc(Config::getConfigName)
            .page(page);

    return SystemUtil.buildResource(page, ConfigListVO.class);
  }
}
